package de.joergviola.mobj.client;

import java.util.logging.Logger;

import com.google.code.gwt.database.client.Database;
import com.google.code.gwt.storage.client.Storage;

import de.joergviola.mobj.client.database.AsyncDBTransaction;
import de.joergviola.mobj.client.database.SchemaTransaction;
import de.joergviola.mobj.client.storage.StorageTransaction;
import de.joergviola.mobj.shared.Schema;

public class LocalDB {

	private static final Logger log = Logger.getLogger("LocalDB");

	private Database db;
	private Storage storage;
	private final Schema schema;

	public LocalDB(Schema schema) {
		this.schema = schema;
		if (Database.isSupported()) {
			log.info("LocalDB: HTML5 Database API available");
			db = Database.openDatabase(schema.getShortName(),
					schema.getVersion(), schema.getDisplayName(),
					schema.getMaxSizeBytes());
			db.transaction(new SchemaTransaction(schema));
		} else if (Storage.isSupported()) {
			log.info("LocalDB: HTML5 Storage API available");
			storage = Storage.getLocalStorage();
		} else {
			log.info("LocalDB: No HTML5 persistence available");
		}
	}

	public ITransaction getLocalTransaction() {
		if (db != null)
			return new AsyncDBTransaction(db, schema);
		if (storage != null)
			return new StorageTransaction(storage, schema);
		return null;
	}
}
